import Module from "./module";
import { forEachValue } from "../utils";
class ModuleCollection {
  constructor(options) {
    this.register([], options); // 递归实现收集要记录父子关系
  }
  getNamespace(path) {
    // 你给我个路径 我就返回给你一个命名空间  //[a,c]
    let root = this.root;
    return path.reduce((memo, moduleName) => {
      root = root.getChild(moduleName); // root._children[a]
      return memo + (root.namespaced ? moduleName + "/" : "");
    }, "");  
  }
  register(path, rootModule) {
    let module = new Module(rootModule); // _raw  _children  state
    rootModule.wrapperModule = module
    if (path.length == 0) {
      this.root = module;
    } else {
      // ['a']    ['b']
      let parent = path.slice(0, -1).reduce((memo, current) => {
        return memo.getChild(current);
      }, this.root);
      parent.addChild(path[path.length - 1], module);
    }
    if (rootModule.modules) {
      // 获取到定义的子模块  ['a','c']
      forEachValue(rootModule.modules, (moduleName, moduleValue) => {
        this.register(path.concat(moduleName), moduleValue);
      });
    }
  }
}
export default ModuleCollection;
